%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LC.M
% This is a Matlab procedure which calculates the LC test
% for parameter instability in linear models as reported
% in Hansen (1992) Journal of Policy Modeling.

% Bruce E. Hansen
% Department of Economics
% Social Science Building
% University of Wisconsin
% Madison, WI 53706-1393
% bhansen@ssc.wisc.edu
% http://www.ssc.wisc.edu/~bhansen/


% The format for the command is

% lc(dat,datname)

% The matrix "dat" is a nx(k+1) matrix, with the dependent
% (y) variable in the first colume, and the independent (x)
% variables in the remaining columes.  If a constant is desired
% in the regression, it should be included in the dat matrix.
% The vector "datname" is a (k+1)x1 list of variable names,
% for the columes of "dat".

% The output is printed to the screen.
function [li,lj]=LC(dat,datname)
n=length(dat(:,1));
k=length(dat(1,:))-1;
y=dat(:,1);
x=dat(:,2:k+1);
m=inv(x'*x);
b=m*(x'*y);
e=y-x*b;
xe=x.*(e*ones(1,length(x(1,:))));
e2=e.^2;
sig2=mean(e2)';
e2m=e2-sig2;
se=[sqrt(diag(m*xe'*xe*m));sqrt(mean(e2m.^2)/n)];
r2=1-sum(e2)/sum((y-mean(y)).^2);
f=[xe,e2m];
s=cumsum(f);
v=f'*f;
lj=sum(sum(s.*(s*inv(v)))')'/n;
li=sum(s.^2)'./diag(v)/n;
datname=[datname(2:k+1,:);'Variance'];
% NomeVar = 'Variance';
% datname=[datname(2:k+1,:); NomeVar(1,1:size(datname,2))];
fprintf('Variable     Estimate     St Error     LC\n');
fprintf('-----------------------------------------\n');
b=[b;sig2];
for i=1:length(se(:,1))
    fprintf('%s   %f   %f   %f\n',datname(i,:),b(i),se(i),li(i));
end;
fprintf('\n\n\n');
fprintf('Joint LC:   %f\n',lj);
fprintf('R-Squred:   %f\n\n\n',r2);
fprintf('**************************************\n\n\n');
